package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
 *优酷官方接口
 * **/
@Slf4j
public class Plugin_ECARD_P002 implements ChannelService {


    public static String getSignStr(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null && item.getKey() != "") {
                    String key = String.valueOf(item.getKey());
                    String val = String.valueOf(item.getValue());
                    if(sb.length()>0){
                        sb.append("&");
                    }
                    if (StringUtils.hasLength(val)) {
                        sb.append(key +"="+ val);
                    }
                }
            }
            result = sb.toString();
        } catch (Exception e) {
            log.error("获取签名明文出错：", e);
            return null;
        }
        return result;
    }
    public String sign(Map<String, String>  params, String secret) {
        String signedData = getSignStr(params);
        String computedSignature = new HmacUtils(HmacAlgorithms.HMAC_MD5, secret).hmacHex(signedData);
        return computedSignature;
    }

    public  ChannelResult QueryBalance(JSONObject apiConfig){
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }
    public  ChannelResult Submit(JSONObject apiConfig, Map<String,Object> data){
        try{
            BigDecimal money=new BigDecimal(String.valueOf(data.get("AgentPrice"))).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_DOWN);
            money=money.stripTrailingZeros();
            String price=money.toPlainString();
            Map<String,Object> attributes=new HashMap<>();
            String[] productCodes=String.valueOf(data.get("SUPProductId")).split("_");
            if (productCodes.length>=2 && "special".equals(productCodes[1])){
                attributes.put("actual_payment_price",String.valueOf(data.get("AgentPrice")));
                data.put("SUPProductId",productCodes[0]);
            }else {
                attributes.put("unitPrice",price);
            }

            DateTimeFormatter dft=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String curTime =dft.format(LocalDateTime.now());
            Map<String, String> dataParams = new HashMap<>();
            dataParams.put("activity_id",String.valueOf(data.get("SUPProductId")));
            dataParams.put("timestamp",curTime);
            /*type为1时     ytid  ytId^ytId   */
            //dataParams.put("ytid",String.valueOf(data.get("AccountVal")));

            String accountVal = String.valueOf(data.get("AccountVal"));
            String[] strings = splitString(accountVal);
            if (strings.length==1){
                dataParams.put("type","2");
                dataParams.put("mobile",String.valueOf(data.get("AccountVal")));
            }else {
                dataParams.put("type","1");
                dataParams.put("ytid",strings[0]);
            }
            dataParams.put("out_order_no",String.valueOf(data.get("ChannelOrderCode")));
            dataParams.put("attributes",JSONObject.toJSONString(attributes));
            String Signature = sign(dataParams, String.valueOf(apiConfig.get("SecretKey")));

            dataParams.put("sign",Signature.toLowerCase());

            String url=apiConfig.getString("SubmitURL");
            String res= HttpTool.HttpPost(url,dataParams);
            JSONObject retobj = JSONObject.parseObject(res);
            JSONObject response=retobj.getJSONObject("youku_public_response");
            String code=response.getString("error");
            String msg=response.getString("msg");
            if ("1".equals(code)){
                  JSONObject result=response.getJSONObject("result");
                  Boolean order_state=result.getBoolean("order_state");
                  if (order_state){
                     return ChannelResult.IN_PROCESS();
                  }else {
                      return ChannelResult.error(code+msg+order_state);
                  }

            }else {
                return ChannelResult.FAILED(code+msg);
            }

        }catch (Exception ex){
            log.error("调用优酷提单接口出错：",ex);
            return ChannelResult.error("优酷提单接口错误");
        }

    }
    public  ChannelResult Query(JSONObject apiConfig,Map<String,Object> data){
        try{
            DateTimeFormatter dft=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String curTime =dft.format(LocalDateTime.now());
            Map<String, String> dataParams = new HashMap<>();
            dataParams.put("activity_id",String.valueOf(data.get("SUPProductId")));
            dataParams.put("timestamp",curTime);
            dataParams.put("out_order_no",String.valueOf(data.get("ChannelOrderCode")));
            String Signature = sign(dataParams, String.valueOf(apiConfig.get("SecretKey")));

            dataParams.put("sign",Signature.toLowerCase());

            String url=apiConfig.getString("QueryURL");
            String res= HttpTool.HttpPost(url,dataParams);
            JSONObject retobj = JSONObject.parseObject(res);
            JSONObject response=retobj.getJSONObject("youku_public_response");
            String code=response.getString("error");
            String msg=response.getString("msg");
            if ("1".equals(code)){
                JSONObject result=response.getJSONObject("result");
                String order_state=result.getString("order_state");
                if ("3".equals(order_state)){
                    return ChannelResult.success("充值成功");
                }else if ("2".equals(order_state)){
                    return ChannelResult.FAILED();
                }else if ("1".equals(order_state)){
                    return ChannelResult.IN_PROCESS();
                }else {
                    return ChannelResult.error(code+msg+order_state);
                }
            }else {
                return ChannelResult.error(code+msg);
            }

        }catch (Exception ex){
            log.error("调用优酷查询接口出错：",ex);
            return ChannelResult.error("优酷查询接口错误");
        }
    }

    public  ChannelResult Notify(JSONObject apiConfig,Map<String,Object> data){
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");

    }

    public static String[] splitString(String input) {
        if (input == null || input.isEmpty()) {
            return new String[]{};
        }
        if (input.contains("^")) {
            return input.split("\\^");
        } else {
            return new String[]{input};
        }
    }


}
